package crmdna;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import crmdna.mail.MandrillEventProp;

@SuppressWarnings("serial")
public class MandrillWebhookServlet extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/plain");
    resp.getWriter().println("Mandrill web hook servlet (get call)");
  }

  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/plain");

    StringBuilder builder = new StringBuilder();
    String line = null;
    try {
      BufferedReader reader = req.getReader();
      while ((line = reader.readLine()) != null)
        builder.append(line);
    } catch (Exception e) { /* report an error */
      resp.getWriter().println("Exception when reading request data");
    }

    Logger logger = Logger.getLogger(MandrillWebhookServlet.class.getName());
    String json = URLDecoder.decode(builder.toString(), "UTF-8");

    // json is of the format: mandrill_events=[{"event":....}]. remove mandrill_events=
    json = json.substring(16);
    logger.info("request data: " + json);

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    MandrillEventProp[] mandrillEventProps = gson.fromJson(json, MandrillEventProp[].class);

    logger.info("mandrillEventProp: " + gson.toJson(mandrillEventProps));

    resp.getWriter().println("Mandrill web hook servlet (post call)");
  }
}
